<template>
  <view class="container">
    <view class="form">
      <view class="row">
        <view class="left">项目名称</view>
        <input class="input" type="text" @input="changeProjectValue" data-field="name" :value="project_data.name" placeholder="请输入项目名称"/>
      </view>
      <view class="row" style="align-items: flex-start">
        <view class="left">简介</view>
        <textarea class="textarea" name="content" @input="changeProjectValue" data-field="content" :value="project_data.content" placeholder="请输入简介"></textarea>
      </view>
      <view class="row">
        <view class="left">承办单位</view>
        <view class="right">
          <view class="unit">{{ info.company_info.company_name }}</view>
          <view class="type">{{ info.company_info.type_desc }}</view>
        </view>
      </view>
      <view class="row">
        <view class="left">适用对象</view>
        <input class="input" type="text" @input="changeProjectValue" data-field="applicable_objects" :value="project_data.applicable_objects" placeholder="如：大学生、中学生"/>
      </view>
      <view class="row">
        <view class="left">联系人</view>
        <input class="input" type="text" @input="changeProjectValue" data-field="head_name" :value="project_data.head_name" placeholder="请输入联系人"/>
      </view>
      <view class="row">
        <view class="left">联系电话</view>
        <input class="input" type="text" @input="changeProjectValue" data-field="head_mobile" :value="project_data.head_mobile" placeholder="请输入联系电话"/>
      </view>
      <view class="row" style="align-items: flex-start">
        <view class="left">岗位信息</view>
        <view class="add-btn" @click="addPost">新增岗位</view>
      </view>
      <view class="row" style="align-items: flex-start; flex-direction: column;width: calc(100% - 210rpx); margin-left: 170rpx;">
        <view class="left"></view>
        <view class="post-box" v-for="(value, index) in post_data" :key="index">
          <image class="del-post" src="/static/images/del.png" @click="delPost(index)"></image>
          <view class="row" style="margin-top: 60rpx">
            <view class="left">名称</view>
            <input class="input" type="text" @input="changePostValue" :data-index="index" data-field="name" :value="value.name" placeholder="请输入名称"/>
          </view>
          <view class="row">
            <view class="left">报名上限</view>
            <input class="input" type="number" @input="changePostValue" :data-index="index" data-field="max_count" :value="value.max_count" placeholder="请输入报名上限"/>
          </view>
          <view class="row">
            <view class="left">辅导员姓名</view>
            <input class="input" type="text" @input="changePostValue" :data-index="index" data-field="counsellor_name" :value="value.counsellor_name" placeholder="请输入辅导员姓名"/>
          </view>
          <view class="row">
            <view class="left">辅导员岗位</view>
            <input class="input" type="text" @input="changePostValue" :data-index="index" data-field="counsellor_unit" :value="value.counsellor_unit" placeholder="请输入辅导员岗位"/>
          </view>
          <view class="row" style="align-items: flex-start">
            <view class="left">体验时间</view>
            <textarea class="textarea" name="content" @input="changePostValue" :data-index="index" data-field="time" :value="value.time" placeholder="X月 X日（周X）XX：XX-XX：XX"></textarea>
          </view>
        </view>
      </view>
      <view class="row">
        <view class="left">结束时间</view>
        <view class="right">
          <picker class="input" mode="date" @change="onDateChange" :value="dateValue">
            <view>{{ dateValue ? dateValue : '请选择结束时间' }}</view>
          </picker>
        </view>
      </view>
      <view class="row">
        <view class="left">地址</view>
        <input class="input" type="text" @input="changeProjectValue" data-field="address" :value="project_data.address" placeholder="请输入地址"/>
      </view>
      <view class="row" style="align-items: flex-start">
        <view class="left">申报资料上传</view>
        <view class="download-list">
          <view class="box" @click="downloadFile(item.file_url, item.all_name)" v-for="(item, index) in info.project_file" :key="index">
            <image class="download" src="../../static/images/download.png"></image>
            <text>{{ item.name }}</text>
          </view>
        </view>
      </view>
      <view class="row" style="align-items: flex-start">
        <view class="left">申报资料</view>
        <view class="download-list">
          <view class="box" @click="deleteFile(index)" v-for="(item, index) in file_arr" :key="index">
            <text class="name">{{ item.name }}</text>
            <image class="del" src="/static/images/del.png"></image>
          </view>
        </view>
      </view>

      <view class="btn-box">
        <view class="button cancel" @click="uploadFiles">上传申报资料</view>
        <button class="button save" @click="submit">立即提交</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      info: [],
      project_data: {},
      post_data: [],
      file_arr: [],
      dateValue: ''
    };
  },

  onLoad: function (options) {
    var company_prove_id = uni.getStorageSync('company_prove_id'),
      id = options.id ? options.id : 0;

    this.$http.post('/index/Api/applyProjectPage', {company_prove_id}).then(res => {
      if (res.data.result == 1) {
        this.info = res.data.data;
      } else {
        this.$common.doErrorResult(res)
        setTimeout(() => {
          uni.navigateBack();
        }, 500)
      }
    })

    if (id > 0) {
      this.$http.post('/index/Api/projectDetail', {id}).then(res => {
        if (res.data.result == 1) {
          this.project_data = res.data.data;
          this.post_data = res.data.data.post_list;

        } else {
          this.$common.doErrorResult(res);
        }
      })
    }
  },

  methods: {
    onDateChange(e) {
      this.dateValue = e.detail.value;
      this.project_data.end_time = `${this.dateValue}`;
    },

    downloadFile: function (url, all_name) {
      uni.showLoading({
        title: '下载中'
      })

      //下载文件
      uni.downloadFile({
        url: url,
        success: (res) => {
          //下载成功
          if (res.statusCode === 200) {
            //保存文件
            let tempFile = res.tempFilePath;
            //保存成功之后 打开文件
            uni.getFileSystemManager().saveFile({
              tempFilePath: tempFile,
              filePath: wx.env.USER_DATA_PATH + '/' + all_name,//自定义文件名
              success(res) {
                wx.hideLoading();
                uni.openDocument({
                  filePath: res.savedFilePath,
                  showMenu: true, //是否可以分享
                  success: (res) => {
                    uni.hideLoading()
                    console.log(res);
                  },
                  fail: (e) => {
                    uni.showToast({
                      title: '打开失败',
                      icon: "error"
                    })
                  }
                })

              }
            })
          }
        },
        fail: (e) => {
          uni.hideLoading();
          uni.showToast({
            title: '文件下载失败',
            icon: "error",
          })
        }
      });

    },

    uploadFiles: function () {
      this.$common.uploadFiles(res => {
        res = JSON.parse(res);
        if (res.status == 1) {
          var file = res.data,
            file_arr = this.file_arr;

          file_arr.push(file);
          this.file_arr = file_arr;

          uni.showToast({
            title: '上传成功',
            duration: 1000
          })
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    },

    changeProjectValue(e) {
      var project_data = this.project_data,
        field = e.currentTarget.dataset.field;

      project_data[field] = e.detail.value;
      this.project_data = project_data;
    },

    addPost: function () {
      var post_data = this.post_data,
        post = {id: 0, name: '', max_count: '', counsellor_name: '', counsellor_unit: '', time: ''};

      post_data.push(post)
    },

    delPost: function (index) {
      var post_data = this.post_data;
      post_data.splice(index, 1);
      this.post_data = post_data;
    },

    changePostValue(e) {
      var post_data = this.post_data,
        index = e.currentTarget.dataset.index,
        field = e.currentTarget.dataset.field;

      post_data[index][field] = e.detail.value;
      this.post_data = post_data;
    },

    deleteFile: function (index) {
      var file_arr = this.file_arr;
      file_arr.splice(index, 1);
      this.file_arr = file_arr;
    },

    submit: function () {
      var project_data = this.project_data,
        post_data = this.post_data,
        file_arr = this.file_arr,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      uni.showLoading({
        title: '提交中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        project_data.user_id = uni.getStorageSync('user_id');
        project_data.file_ids = file_arr.length > 0 ? file_arr.map(item => item.id).join(',') : '';
        project_data.post_data = post_data;

        this.$http.post('/index/Api/doProject', project_data).then(res => {
          uni.removeStorageSync('timestamp');
          uni.hideLoading();

          if (res.data.result == 1) {
            uni.showToast({
              title: res.data.msg,
              success: () => {
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/project_manage/project_manage'
                  })
                }, 500)
              }
            })
          } else {
            this.$common.doErrorResult(res);
          }
        })
      }
    },
  },
}
</script>


<style lang="scss">
.container {
  padding: 20rpx 0;
  background: #fff;

  .form {
    padding: 0 20rpx;

    .row {
      display: flex;
      padding-top: 20rpx;
      align-items: center;

      .add-btn {
        font-size: 24rpx;
        color: #fff;
        background: #32a4ff;
        width: 120rpx;
        height: 60rpx;
        line-height: 60rpx;
        padding: 0 24rpx;
        border-radius: 50rpx;
        text-align: center;
      }

      .left {
        width: 170rpx;
      }

      .right {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 24rpx;
        color: #3D3D3D;
        flex: 1;

        .type {
          padding: 2rpx 10rpx;
          border-radius: 10rpx;
          background: #B574FF;
          color: #fff;
        }

        picker{
          padding: 16rpx 20rpx;
        }
      }

      .input, textarea {
        flex: 1;
        border: 1rpx solid #f5f5f5;
        border-radius: 10rpx;
        padding: 10rpx 20rpx;
      }

      .download-list {
        margin-left: 20rpx;
        width: calc(100% - 210rpx);

        .box {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;

          .name {
            width: 90%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .download {
            width: 30rpx;
            height: 30rpx;
            margin-right: 10rpx;
          }

          .del {
            width: 50rpx;
            height: 50rpx;
            margin-left: 20rpx;
          }

          text {
            color: #3D3D3D;
          }
        }
      }
    }

    .post-box {
      border: 1rpx solid #f5f5f5;
      padding: 0 20rpx 20rpx 20rpx;
      width: 100%;
      min-width: 0;
      position: relative;
      margin-bottom: 20rpx;

      .del-post {
        position: absolute;
        width: 60rpx;
        height: 60rpx;
        top: 10rpx;
        right: 10rpx;
      }

    }

    .btn-box {
      display: flex;
      justify-content: space-between;
      width: 100%;
      margin-top: 40rpx;

      .button {
        font-size: 32rpx;
        flex: 1;
        text-align: center;
        border-radius: 50rpx;
      }

      .cancel {
        background: #fff;
        padding: 20rpx 40rpx;
        color: #32A4FF;
        border: 1rpx solid #32A4FF;
      }

      .save {
        background: #32A4FF;
        color: #fff;
        margin-left: 40rpx;
        border: none;
        outline: none;
      }
    }
  }

}

</style>

